package com.mall.api.controller;

import com.category.spi.model.Category;
import com.category.spi.model.CategoryTreeDTO;
import com.category.spi.service.CategoryService;
import com.mall.api.service.ProductFeignClientService;
import com.mall.common.util.JsonResult;
import com.mall.model.Product;
import io.swagger.v3.core.util.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.function.EntityResponse;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/categories")
public class CategoryController {
    @Autowired
    CategoryService categoryService;

    @Autowired
    ProductFeignClientService productFeignClientService;

    @GetMapping("/ping")
    public String ok() {
        return "ok";
    }

    /** 新增分类（顶级或子级） */
    @PostMapping
    public JsonResult<Long> create(@RequestBody Category category) {
        return JsonResult.success(categoryService.create(category));
    }

    /** 更新分类（按ID） */
    @PutMapping("/{id}")
    public JsonResult<Boolean> update(@PathVariable("id") Long id, @RequestBody Category category) {
        category.setId(id);
        return JsonResult.success(categoryService.updateById(category));
    }

    /** 详情 */
    @GetMapping("/{id}")
    public JsonResult<Category> detail(@PathVariable("id") Long id) {
        return JsonResult.success(categoryService.getById(id));
    }

    /** 分页列表（名称/slug/父ID/层级/状态） */
    @GetMapping
    public JsonResult<Map<String, Object>> list(
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "parentId", required = false) Long parentId,
            @RequestParam(value = "level", required = false) Integer level,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size) {

        List<Category> data = categoryService.pageQuery(keyword, parentId, level, status, page, size);
        long total = categoryService.count(keyword, parentId, level, status);
        Map<String, Object> res = new HashMap<>();
        res.put("total", total);
        res.put("list", data);
        return JsonResult.success(res);
    }

    /** 直接子类列表（parentId 为空则取顶级） */
    @GetMapping("/children")
    public JsonResult<List<Category>> children(
            @RequestParam(value = "parentId", required = false) Long parentId,
            @RequestParam(value = "status", required = false) Integer status) {
        return JsonResult.success(categoryService.listChildren(parentId, status));
    }

    /** 树（包含 children 嵌套结构，按 sort_order asc, id asc 排序） */
    @GetMapping("/tree")
    public JsonResult<List<CategoryTreeDTO>> tree(@RequestParam(value = "status", required = false) Integer status) {
        return JsonResult.success(categoryService.tree(status));
    }

    /** 移动分类（更换父级） */
    @PatchMapping("/{id}/move")
    public JsonResult<Boolean> move(@PathVariable("id") Long id,
                                    @RequestParam(value = "newParentId", required = false) Long newParentId) {
        return JsonResult.success(categoryService.move(id, newParentId));
    }

    /** 软删除（默认：存在子类则禁止删除） */
    @DeleteMapping("/{id}")
    public JsonResult<Boolean> delete(@PathVariable("id") Long id) {
        return JsonResult.success(categoryService.softDelete(id));
    }


    @GetMapping("/{id}/products")
    public ResponseEntity<JsonResult<?>> getProductByCategory(@PathVariable("id") Long id, @RequestParam(required = false) Integer status) {
        try {
            // 明确泛型，确保类型一致
            JsonResult<List<Product>> result = productFeignClientService.getProductByCategoryId(id, status);
            if (result == null) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.ok(JsonResult.fail("调用异常"));
            }
        } catch (Exception e) {
            // 捕获异常，返回错误结果
            return ResponseEntity.ok(JsonResult.fail("调用失败"));
        }
    }
    @GetMapping("/list")
    public ResponseEntity<JsonResult<?>>getCategoryList() {

           List<Category> result = categoryService.listChildren(null,1);
           if(result == null) {
               return  ResponseEntity.ok(JsonResult.fail("调用失败"));
           } else {
               return  ResponseEntity.ok(JsonResult.success(result));
           }


    }
}
